package jmind.core.poi;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jmind.core.poi.Excel.Version;
import jmind.core.util.RequestUtil;

import org.apache.poi.ss.usermodel.Workbook;

public class PoiExportUtil {

    /**
     * 
     * @param request
     * @param response
     * @param list  数据
     * @param fileName Excel名字
     * @param sheetName  
     * @param headers 表头
     * @param methods  字段方法名
     */
    public static <T> void export(HttpServletRequest request, HttpServletResponse response, String fileName,
            Version version, String sheetName, List<T> list, String[] headers, String[] methods) {
        // 进行转码，使其支持中文文件名
        RequestUtil.setExcelHeader(fileName + "." + version.name(), request, response);
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            Workbook workbook = null;
            if (methods == null) {
                workbook = Excel.getExcel(version).exportExcel(sheetName, list, headers);
            } else {
                workbook = Excel.getExcel(version).exportExcel(sheetName, list, headers, methods);
            }

            if (workbook != null)
                workbook.write(out);

        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                out.flush();
                out.close();
            } catch (Exception e2) {
                throw new RuntimeException(e2);
            }
        }

    }

    public static void export(HttpServletRequest request, HttpServletResponse response, String fileName,
            Version version, String sheetName, List<?> list) {
        // 进行转码，使其支持中文文件名
        RequestUtil.setExcelHeader(fileName + "." + version.name(), request, response);
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            Workbook workbook = Excel.getExcel(version).exportExcel(sheetName, list);
            if (workbook != null)
                workbook.write(out);

        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                out.flush();
                out.close();
            } catch (Exception e2) {
                throw new RuntimeException(e2);
            }
        }
    }

}
